<template>
  <view class="w-full">
    <view class="flex justify-between items-center p-4">
      <text class="text-lg font-bold">居家医护</text>
      <!-- <nut-button size="mini" type="primary" @click="autoClickFirstLevel3Item">
        自动点击
      </nut-button> -->
    </view>

    <view class="px-2 box-border flex flex-nowrap overflow-x-auto gap-[10rpx] mb-2">
      <view v-if="professionLoading" class="text-center text-gray-500 py-4">
        <text>加载职业类型中...</text>
      </view>
      <view
        v-else
        v-for="(item, i) in professionList"
        :key="i"
        :class="selectedNurseIndex === i ? 'active' : ''"
        class="notm"
        @click="onProfessionClick(i)"
      >
        {{ item }}
      </view>
    </view>
    
    <ThreeLevelDirectory 
      ref="directoryRef"
      :show-add-button="true"
      :add-button-text="addButtonText"
      @change="onDirectoryChange"
      @add="onAddItem">
      
      <!-- 内容插槽 -->
      <template #content="{ currentItem, level1, level2 }">
        <view v-if="loading" class="text-center text-gray-500 py-8">
          <text>加载中...</text>
        </view>
        
        <view v-else-if="currentItem && nurseList.length > 0" class="two-column-layout">
          <view class="item-card" v-for="item in nurseList" :key="item.id" @click="onNurseClick(item)">
            <image :src="getAvatar(item.avatar) || defaultAvatar" mode="aspectFit" class="item-image"></image>
            <view class="mt-2">
              <text class="text-[24rpx] text-[#999] truncate">{{ item.name || '未知' }}</text>
            </view>
          </view>
        </view>
        
        <view v-else class="text-center text-gray-500 py-8">
          <text>{{ currentItem ? '暂无数据' : '请选择三级目录项查看内容' }}</text>
        </view>
      </template>
    </ThreeLevelDirectory>

    <!-- 添加标签弹窗 -->
    <nut-popup 
      v-model:visible="showAddPopup" 
      position="center" 
      :style="{ width: '80%', borderRadius: '24rpx' }"
    >
      <view class="add-popup">
        <view class="popup-header">
          <text class="popup-title">添加{{ addLevelText }}</text>
        </view>
        
        <view class="popup-content">
          <nut-input
            v-model="addTagName"
            :placeholder="`请输入${addLevelText}名称`"
            :maxlength="50"
            clearable
            class="tag-input"
          />
        </view>
        
        <view class="popup-footer">
          <nut-button 
            type="default" 
            class="flex-1"
            @click="closeAddPopup"
          >
            取消
          </nut-button>
          <nut-button 
            type="primary" 
            class="flex-1 ml-3"
            @click="confirmAddTag"
          >
            确定
          </nut-button>
        </view>
      </view>
    </nut-popup>
  </view>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import ThreeLevelDirectory from "./ThreeLevelDirectory.vue";
import { request } from "@/service/request";
import Taro from "@tarojs/taro";
import defaultAvatar from "@/assets/img/bao.png";
import { useImage } from '@/hooks'
import { getJobVisibleList } from '@/service/api/nurse_user'
import { PlatformUtils } from '@/utils/channel'

const getAvatar = (avatar) => {
  if (avatar) {
    return useImage(avatar);
  }
  return defaultAvatar;
};

// 添加按钮文本配置
const addButtonText = ref({
  level1: "添加部门",
  level2: "添加科室",
  level3: "添加项目"
});

// 职业类型列表
const professionList = ref([]);
const professionLoading = ref(false);

// 护士列表数据
const nurseList = ref([]);
const loading = ref(false);
const currentSelectedItem = ref(null);

// 选中的职业索引
const selectedNurseIndex = ref(0);

// 三级目录组件ref
const directoryRef = ref(null);

// 添加标签弹窗相关
const showAddPopup = ref(false);
const addTagName = ref('');
const addLevelText = ref('');
const addParentId = ref(null);

// 获取职业类型列表
const getProfessionList = async () => {
  try {
    professionLoading.value = true;
    const hospitalId = PlatformUtils.getHospitalId();
    
    if (!hospitalId) {
      // console.error('未找到医院ID');
      Taro.showToast({
        title: '未找到医院信息',
        icon: 'none'
      });
      return;
    }
    
    // console.log('获取职业类型列表, hospitalId:', hospitalId);
    
    const res = await getJobVisibleList(hospitalId);
    
    // console.log('职业类型列表数据:', res);
    
    if (res.success && res.success.records) {
      professionList.value = res.success.records[0].mode_dictText.split(',');
      // professionList.value = res.success.records.map(item => item.name || item.jobName || item.title);
    } else if (res.success && Array.isArray(res.success)) {
      professionList.value = res.success.map(item => item.name || item.jobName || item.title);
    } else {
      // 如果接口返回空，使用默认的职业列表
      professionList.value = [
        '医生',
        '护士',
        '康复师',
        '技师',
      ];
    }
    
    // 加载完成后，默认切换到"护士"职业
    const nurseIndex = professionList.value.findIndex(item => item === '护士');
    if (nurseIndex !== -1) {
      selectedNurseIndex.value = nurseIndex;
      // console.log('默认切换到护士职业, 索引:', nurseIndex);
    }
  } catch (error) {
    // console.error('获取职业类型列表失败:', error);
    // 使用默认的职业列表作为备选
    professionList.value = [
      '医生',
      '护士',
    //   '康复师',
    //   '技师',
    //   '药剂师',
    //   '营养师',
    //   '心理咨询师',
    //   '社工师',
    //   '医疗护理员',
    //   '养老护理员',
    //   '母婴护理员',
    //   '新家政服务员',
    //   '老家政服务员',
    //   '辅助人员'
    ];
    
    // 加载完成后，默认切换到"护士"职业
    const nurseIndex = professionList.value.findIndex(item => item === '护士');
    if (nurseIndex !== -1) {
      selectedNurseIndex.value = nurseIndex;
      // console.log('默认切换到护士职业, 索引:', nurseIndex);
    }
  } finally {
    professionLoading.value = false;
  }
};

// 组件挂载时获取职业类型列表
onMounted(() => {
  getProfessionList();
  
  // 延时4秒后自动点击第一个三级项目
  setTimeout(() => {
    autoClickFirstLevel3Item();
  }, 4000);
});

// 自动点击第一个三级项目
const autoClickFirstLevel3Item = () => {
  // console.log('🔄 延时4秒后，尝试自动点击第一个三级项目...');
  
  if (!directoryRef.value) {
    // console.log('❌ 目录组件引用不存在');
    return;
  }
  
  const level3List = directoryRef.value.level3List;
  // console.log('第三级列表:', level3List);
  
  if (level3List && level3List.length > 0) {
    const firstItem = level3List[0];
    // console.log('找到第一个三级项目:', firstItem);
    
    if (!firstItem.isAddButton) {
      // console.log('✅ 自动点击第一个三级项目:', firstItem);
      // 触发目录变化事件
      onDirectoryChange({ level: 3, item: firstItem });
    } else {
      // console.log('⚠️ 第一个项目是添加按钮，跳过');
    }
  } else {
    // console.log('❌ 第三级列表为空或不存在');
    
    // 如果第三级列表为空，尝试手动触发刷新
    if (directoryRef.value.refresh) {
      // console.log('🔄 尝试刷新目录组件...');
      directoryRef.value.refresh();
      
      // 再次延时检查
      setTimeout(() => {
        autoClickFirstLevel3Item();
      }, 2000);
    }
  }
};

// 等待指定级别的数据加载完成
const waitForLevelData = (level, maxWaitTime = 5000) => {
  return new Promise((resolve, reject) => {
    const startTime = Date.now();
    
    const checkData = () => {
      if (!directoryRef.value) {
        reject(new Error('目录组件引用不存在'));
        return;
      }
      
      let hasData = false;
      let listLength = 0;
      
      if (level === 1) {
        hasData = directoryRef.value.level1List && directoryRef.value.level1List.length > 0;
        listLength = directoryRef.value.level1List?.length || 0;
      } else if (level === 2) {
        hasData = directoryRef.value.level2List && directoryRef.value.level2List.length > 0;
        listLength = directoryRef.value.level2List?.length || 0;
      } else if (level === 3) {
        hasData = directoryRef.value.level3List && directoryRef.value.level3List.length > 0;
        listLength = directoryRef.value.level3List?.length || 0;
      }
      
      // console.log(`⏳ 等待第${level}级数据... 当前长度: ${listLength}`);
      
      if (hasData) {
        // console.log(`✅ 第${level}级数据加载完成，长度: ${listLength}`);
        resolve();
      } else if (Date.now() - startTime > maxWaitTime) {
        // console.log(`⏰ 等待第${level}级数据超时`);
        reject(new Error(`等待第${level}级数据超时`));
      } else {
        setTimeout(checkData, 500);
      }
    };
    
    checkData();
  });
};

// 监听职业类型列表变化，当有数据时延迟自动点击
watch(professionList, (newList) => {
  if (newList && newList.length > 0) {
    // console.log('职业类型列表加载完成，延迟3秒后自动点击...');
    setTimeout(() => {
      autoClickFirstLevel3Item();
    }, 3000);
  }
}, { deep: true });

// 监听目录组件引用，当组件可用时延迟自动点击
watch(directoryRef, (newRef) => {
  if (newRef) {
    // console.log('目录组件引用已设置，延迟2秒后自动点击...');
    setTimeout(() => {
      autoClickFirstLevel3Item();
    }, 2000);
  }
});

// 获取护士列表
const getNurseList = async (tagId) => {
  try {
    loading.value = true;
    // console.log("获取护士列表, tagId:", tagId, professionList.value[selectedNurseIndex.value]);
    
    const params = {
      pageSize: 12,
      pageNo: 1,
      projectid: tagId,
      // isHealth: 1,
      job: professionList.value[selectedNurseIndex.value],
      status: 1
    };
    
    // 如果有tagId，添加到参数中
    if (tagId) {
      params.tagId = tagId;
    }
    
    const res = await request.get('/nurse_nurses/nurseNurses/list', params, {
      useErrMsg: true
    });
    
    // console.log("护士列表数据:", res);
    
    if (res.success && res.success.records) {
      nurseList.value = res.success.records;
    } else if (res.success && Array.isArray(res.success)) {
      nurseList.value = res.success;
    } else {
      nurseList.value = [];
    }
  } catch (error) {
    // console.error("获取护士列表失败:", error);
    nurseList.value = [];
  } finally {
    loading.value = false;
  }
};

// 目录变化事件
const onDirectoryChange = ({ level, item }) => {
  // console.log(`📁 目录变化 - 级别${level}:`, item);
  currentSelectedItem.value = item;
  
  // 第三级目录变化时，获取护士列表
  if (level === 3 && item && !item.isAddButton) {
    // console.log('🎯 三级目录变化，立即加载护士列表:', item);
    getNurseList(item.id);
  } else if (level === 3 && !item) {
    // console.log('⚠️ 三级目录为空，清空护士列表');
    nurseList.value = [];
  }
};

const onProfessionClick = (index) => {
  selectedNurseIndex.value = index;
  setTimeout(() => {
    // 如果有当前选中的项目，使用其ID，否则不传递tagId
    const tagId = currentSelectedItem.value?.id;
    // console.log("职业切换，当前tagId:", tagId);
    getNurseList(tagId);
  }, 300);
  // if (directoryRef.value && directoryRef.value.refresh) {
  //   directoryRef.value.refresh();
  // }
};

// 添加项目事件
const onAddItem = ({ level, parentId }) => {
  console.log(`添加项目 - 级别${level}, 父级ID:`, parentId);
  
  const levelText = level === 1 ? '部门' : level === 2 ? '科室' : '项目';
  
  // 设置弹窗数据
  addLevelText.value = levelText;
  addParentId.value = parentId;
  addTagName.value = '';
  
  // 显示弹窗
  showAddPopup.value = true;
};

// 关闭添加弹窗
const closeAddPopup = () => {
  showAddPopup.value = false;
  addTagName.value = '';
};

// 确认添加
const confirmAddTag = async () => {
  const name = addTagName.value.trim();
  
  if (!name) {
    Taro.showToast({
      title: '名称不能为空',
      icon: 'none'
    });
    return;
  }
  
  // 关闭弹窗
  showAddPopup.value = false;
  
  // 调用接口添加
  await addTag(name, addParentId.value, addLevelText.value);
};

// 添加标签
const addTag = async (name, pid, levelText) => {
  try {
    Taro.showLoading({
      title: '添加中...'
    });
    
    const params = {
      name,
      projectid: pid || null
    };
    
    // console.log('添加标签参数:', params);
    
    const res = await request.post('/health_records/health_tag_info/healthTagInfo/add', params, {
      useErrMsg: true
    });
    
    // console.log('添加标签结果:', res);
    
    if (res.success) {
      Taro.hideLoading();
      Taro.showToast({
        title: `${levelText}添加成功`,
        icon: 'success'
      });
      
      // 刷新三级目录数据
      setTimeout(() => {
        if (directoryRef.value && directoryRef.value.refresh) {
          directoryRef.value.refresh();
        }
      }, 1500);
    } else {
      Taro.hideLoading();
      Taro.showToast({
        title: res.message || '添加失败',
        icon: 'none'
      });
    }
  } catch (error) {
    // console.error('添加标签失败:', error);
    Taro.hideLoading();
    Taro.showToast({
      title: '添加失败',
      icon: 'none'
    });
  }
};

// 护士点击事件
const onNurseClick = (nurse) => {
  // console.log('点击护士:', nurse);
  
  // 跳转到护士详情页
  Taro.navigateTo({
    url: `/package-other/nurses/detail?id=${nurse.id}`
  });
};
</script>

<style lang="scss">
.notm{
  white-space: nowrap;
  padding: 10rpx 20rpx;
  border-bottom: 2rpx solid #f0f0f0;
  color: #999;
  &.active{
    color: #0667f8;
    border-bottom: 2rpx solid #0667f8;
  }
}
.two-column-layout {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  
  .item-card {
    flex: 0 0 calc(30% - 8rpx);
    padding: 20rpx 10rpx;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    
    .item-image {
      width: 112rpx;
      height: 112rpx;
      border-radius: 50%;
      border: solid 4rpx #999;
      background-color: #fff;
      display: block;
      flex-shrink: 0;
    }
  }
}

.add-popup {
  padding: 32rpx;
  
  .popup-header {
    text-align: center;
    padding-bottom: 24rpx;
    border-bottom: 1rpx solid #f0f0f0;
    margin-bottom: 32rpx;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .popup-content {
    padding: 16rpx 0;
    
    .tag-input {
      :deep(.nut-input) {
        border: 1rpx solid #e0e0e0;
        border-radius: 12rpx;
        padding: 16rpx 24rpx;
        font-size: 28rpx;
      }
    }
  }
  
  .popup-footer {
    display: flex;
    gap: 24rpx;
    margin-top: 32rpx;
    
    .nut-button {
      flex: 1;
      height: 80rpx;
      border-radius: 12rpx;
      font-size: 28rpx;
    }
  }
}
</style>
